# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
uuid    = require 'uuid'
router = express.Router()
module.exports = router

router.get '/', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select * from pay_o_071 limit 1", defer err, result
    if err then done(client); return next(err)

    # 如果还没有配置，则自动生成默认配置
    if result.rows.length == 0
        await client.query \
            "insert into pay_o_071 (
                uuid,
                url_front, url_back, url_card, url_query,
                url_batch, url_file, url_app,
                back_notify_url,
                notes
            ) values (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10
            )", [
                uuid.v4(), '', '', '', '', '', '', '', '', '默认配置'
            ], defer err, result
        if err then done(client); return next(err)
        done()
        return res.redirect '/o/071'
    else
        done()
        return res.render 'o/071', record: result.rows[0]


router.post '/edit', (req, res, next) ->
    for k in ['uuid']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update pay_o_071 set
            url_front = $1, url_back = $2, url_card  = $3, url_query = $4,
            url_batch = $5, url_file = $6, url_app = $7, back_notify_url = $8,
            timeout = $9, chnl_type = $10, v13_enc = $11, notes = $12
        where uuid = $13", [
            req.body.url_front, req.body.url_back,
            req.body.url_card,  req.body.url_query,
            req.body.url_batch, req.body.url_file,
            req.body.url_app,   req.body.back_notify_url,
            req.body.timeout,   req.body.chnl_type,
            req.body.v13_enc is 'on', req.body.notes,
            req.body.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect '/o/071'


router.post '/disable', (req, res, next) ->
    res.type('json')
    for k in ['uuid']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update pay_o_071 set disabled = $1 where uuid = $2", [
            req.body.disabled, req.body.uuid,
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.json succ: true, redirect: '/o/071'
